<template>
  <div class="main-page">
    <div class="banner">
      <h1>智能健康系统</h1>
      <p class="subtitle">问卷调查 · 文章管理 · 健康服务</p>
    </div>
    
    <div class="feature-cards">
      <div class="feature-card">
        <div class="card-icon">📋</div>
        <h2>问卷调查</h2>
        <p>创建、分享和填写健康调查问卷，收集反馈并分析结果</p>
        <router-link to="/list" class="btn btn-primary">开始使用</router-link>
      </div>
      
      <div class="feature-card">
        <div class="card-icon">📝</div>
        <h2>文章管理</h2>
        <p>发布、编辑和管理健康相关文章，分享专业知识</p>
        <router-link to="/article/list" class="btn btn-primary">浏览文章</router-link>
      </div>
      
      <div class="feature-card">
        <div class="card-icon">💤</div>
        <h2>睡眠记录</h2>
        <p>记录和追踪您的睡眠质量，获取改善建议</p>
        <router-link to="/list" class="btn btn-primary">即将推出</router-link>
      </div>
    </div>
    
    <div class="recent-articles">
      <h2>最新文章</h2>
      <div v-if="loading" class="loading">加载中...</div>
      <div v-if="error" class="error">{{ error }}</div>
      <div v-if="!loading && recentArticles.length === 0" class="empty-message">暂无文章</div>
      <div class="article-grid" v-if="recentArticles.length > 0">
        <div v-for="article in recentArticles" :key="article.id" class="recent-article-card">
          <div class="article-cover" v-if="article.coverImage">
            <img :src="getImageUrl(article.coverImage)" :alt="article.title">
          </div>
          <div class="article-info">
            <h3>{{ article.title }}</h3>
            <p class="article-meta">
              <span v-if="article.author">{{ article.author }}</span>
              <span v-if="article.publishTime">{{ formatDate(article.publishTime) }}</span>
            </p>
            <p class="article-preview">{{ getContentPreview(article.content) }}</p>
            <router-link :to="`/article/view/${article.id}`" class="read-more">
              阅读全文
            </router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted } from 'vue';

export default defineComponent({
  name: 'MainPage',
  setup() {
    const recentArticles = ref([]);
    const loading = ref(true);
    const error = ref('');
    
    const fetchRecentArticles = async () => {
      try {
        const response = await fetch('http://localhost:9001/api/article/list');
        if (!response.ok) {
          throw new Error('获取文章列表失败');
        }
        
        const data = await response.json();
        // 修复：根据接口返回结构赋值，确保 recentArticles.value 一定为数组
        let articlesArr = [];
        if (data && data.code === 1 && data.data && Array.isArray(data.data.list)) {
          articlesArr = data.data.list;
        } else if (Array.isArray(data)) {
          articlesArr = data;
        }
        // 只显示最新的3篇文章
        recentArticles.value = articlesArr.slice(0, 3);
      } catch (err) {
        console.error('获取文章失败:', err);
        error.value = '无法加载最新文章';
      } finally {
        loading.value = false;
      }
    };
    
    const getImageUrl = (path) => {
      if (!path) return '';
      if (/^https?:\/\//.test(path)) return path;
      if (!path.startsWith('/image')) {
        return '/image' + path.replace(/^\/static/, '');
      }
      return path;
    };
    
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: 'numeric', 
        day: 'numeric'
      });
    };
    
    const getContentPreview = (content) => {
      if (!content) return '';
      // 移除Markdown语法并获取前80个字符
      const plainText = content.replace(/[#*`_~]/g, '').replace(/\n/g, ' ');
      return plainText.length > 80 ? plainText.substring(0, 80) + '...' : plainText;
    };
    
    onMounted(fetchRecentArticles);
    
    return {
      recentArticles,
      loading,
      error,
      getImageUrl,
      formatDate,
      getContentPreview
    };
  }
});
</script>

<style scoped>
.main-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.banner {
  text-align: center;
  padding: 40px 20px;
  margin-bottom: 40px;
  background-color: #f0f7ed;
  border-radius: 8px;
}

.banner h1 {
  font-size: 2.5em;
  color: #2E7D32;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 1.2em;
  color: #555;
}

.feature-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 30px;
  margin-bottom: 50px;
}

.feature-card {
  background-color: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  text-align: center;
  transition: all 0.3s ease;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0,0,0,0.1);
}

.card-icon {
  font-size: 40px;
  margin-bottom: 15px;
}

.feature-card h2 {
  margin-bottom: 15px;
  color: #333;
}

.feature-card p {
  color: #666;
  margin-bottom: 20px;
}

.btn {
  display: inline-block;
  padding: 10px 20px;
  border-radius: 4px;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s;
}

.btn-primary {
  background-color: #4CAF50;
  color: white;
}

.btn-primary:hover {
  background-color: #388E3C;
}

.recent-articles {
  margin-top: 40px;
}

.recent-articles h2 {
  text-align: center;
  margin-bottom: 30px;
  font-size: 1.8em;
  color: #333;
}

.article-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 25px;
}

.recent-article-card {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  transition: all 0.3s ease;
}

.recent-article-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0,0,0,0.1);
}

.article-cover {
  height: 180px;
  overflow: hidden;
}

.article-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.recent-article-card:hover .article-cover img {
  transform: scale(1.05);
}

.article-info {
  padding: 20px;
}

.article-info h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 1.2em;
}

.article-meta {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
}

.article-preview {
  color: #444;
  margin-bottom: 15px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.read-more {
  color: #4CAF50;
  text-decoration: none;
  font-weight: 500;
  display: inline-block;
  padding-top: 5px;
}

.read-more:hover {
  text-decoration: underline;
}

.loading, .error, .empty-message {
  text-align: center;
  padding: 30px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-bottom: 20px;
}

.error {
  background-color: #ffebee;
  color: #c62828;
}

@media (max-width: 768px) {
  .article-grid {
    grid-template-columns: 1fr;
  }
  
  .feature-cards {
    grid-template-columns: 1fr;
  }
  
  .banner h1 {
    font-size: 2em;
  }
  
  .banner {
    padding: 30px 15px;
  }
}
</style> 